package br.com.base.business.impl.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;

public class UtilFile {

	public static byte[] getFileToByte(File file) throws Exception{

		FileInputStream fileInputStream=null;

		byte[] arquivo = new byte[(int) file.length()];

		try {
			fileInputStream = new FileInputStream(file);
			fileInputStream.read(arquivo);
			fileInputStream.close();
		}catch(Exception e){
			e.printStackTrace();
			throw e;
		}finally{
			if(fileInputStream != null){
				try {
					fileInputStream.close();
				} catch (IOException e) {
					throw e;
				}
			}
		}
		return arquivo;
	}

	public static byte[] getFileToByte(String file) throws Exception{
		return getFileToByte(new File(file));
	}

	public static String readFile(String path){
		StringBuilder str = new StringBuilder();
		File file = new File(path);
		if(file.exists()){
			String sCurrentLine;
			BufferedReader read = null;
			try{
				read = new BufferedReader(new FileReader(path));
				while ((sCurrentLine = read.readLine()) != null) {
					str.append(sCurrentLine);
				}
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				if(read != null){
					try {
						read.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}

		}
		return str.toString();
	}

	public static void writerFile(byte[] bytes, File file){
		try{
			if(!file.exists()){
				file.createNewFile();
			}
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(bytes);
			fos.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}

}
